package com.lifeverse.repository;

import com.lifeverse.entity.Rule;
import com.lifeverse.entity.enums.RulePriority;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 规则数据访问接口
 */
@Repository
public interface RuleRepository extends JpaRepository<Rule, Long> {
    
    /**
     * 根据名称查找规则
     */
    Optional<Rule> findByName(String name);
    
    /**
     * 根据分类查找规则
     */
    List<Rule> findByCategory(String category);
    
    /**
     * 根据优先级查找规则
     */
    List<Rule> findByPriority(RulePriority priority);
    
    /**
     * 根据启用状态查找规则
     */
    List<Rule> findByEnabled(Boolean enabled);
    
    /**
     * 查找启用的规则
     */
    List<Rule> findByEnabledTrue();
    
    /**
     * 查找禁用的规则
     */
    List<Rule> findByEnabledFalse();
    
    /**
     * 根据分类和启用状态查找规则
     */
    List<Rule> findByCategoryAndEnabled(String category, Boolean enabled);
    
    /**
     * 根据优先级和启用状态查找规则
     */
    List<Rule> findByPriorityAndEnabled(RulePriority priority, Boolean enabled);
    
    /**
     * 根据作者查找规则
     */
    List<Rule> findByAuthor(String author);
    
    /**
     * 查找有效的规则（启用且在有效期内）
     */
    @Query("SELECT r FROM Rule r WHERE r.enabled = true AND " +
           "(r.validFrom IS NULL OR r.validFrom <= :now) AND " +
           "(r.validUntil IS NULL OR r.validUntil > :now)")
    List<Rule> findValidRules(@Param("now") LocalDateTime now);
    
    /**
     * 根据分类查找有效的规则
     */
    @Query("SELECT r FROM Rule r WHERE r.category = :category AND r.enabled = true AND " +
           "(r.validFrom IS NULL OR r.validFrom <= :now) AND " +
           "(r.validUntil IS NULL OR r.validUntil > :now)")
    List<Rule> findValidRulesByCategory(@Param("category") String category, @Param("now") LocalDateTime now);
    
    /**
     * 根据优先级排序查找启用的规则
     */
    @Query("SELECT r FROM Rule r WHERE r.enabled = true ORDER BY r.priority DESC, r.name ASC")
    List<Rule> findEnabledRulesOrderByPriority();
    
    /**
     * 根据分类和优先级排序查找启用的规则
     */
    @Query("SELECT r FROM Rule r WHERE r.category = :category AND r.enabled = true ORDER BY r.priority DESC, r.name ASC")
    List<Rule> findEnabledRulesByCategoryOrderByPriority(@Param("category") String category);
    
    /**
     * 查找高优先级规则
     */
    @Query("SELECT r FROM Rule r WHERE r.enabled = true AND r.priority IN :highPriorities ORDER BY r.priority DESC")
    List<Rule> findHighPriorityRules(@Param("highPriorities") List<RulePriority> highPriorities);
    
    /**
     * 查找最近执行的规则
     */
    @Query("SELECT r FROM Rule r WHERE r.lastExecutedAt IS NOT NULL ORDER BY r.lastExecutedAt DESC")
    List<Rule> findRecentlyExecutedRules(Pageable pageable);
    
    /**
     * 查找成功率高的规则
     */
    @Query("SELECT r FROM Rule r WHERE r.executionCount > 0 AND (r.successCount * 1.0 / r.executionCount) >= :successRateThreshold")
    List<Rule> findHighSuccessRateRules(@Param("successRateThreshold") double successRateThreshold);
    
    /**
     * 查找成功率低的规则
     */
    @Query("SELECT r FROM Rule r WHERE r.executionCount > :minExecutions AND (r.successCount * 1.0 / r.executionCount) < :successRateThreshold")
    List<Rule> findLowSuccessRateRules(@Param("minExecutions") long minExecutions, 
                                     @Param("successRateThreshold") double successRateThreshold);
    
    /**
     * 查找从未执行过的规则
     */
    List<Rule> findByExecutionCount(Long executionCount);
    
    /**
     * 查找长时间未执行的规则
     */
    @Query("SELECT r FROM Rule r WHERE r.enabled = true AND " +
           "(r.lastExecutedAt IS NULL OR r.lastExecutedAt < :threshold)")
    List<Rule> findStaleRules(@Param("threshold") LocalDateTime threshold);
    
    /**
     * 根据版本查找规则
     */
    List<Rule> findByRuleVersion(String ruleVersion);
    
    /**
     * 查找即将过期的规则
     */
    @Query("SELECT r FROM Rule r WHERE r.validUntil IS NOT NULL AND r.validUntil BETWEEN :now AND :threshold")
    List<Rule> findExpiringRules(@Param("now") LocalDateTime now, @Param("threshold") LocalDateTime threshold);
    
    /**
     * 统计分类下的规则数量
     */
    long countByCategory(String category);
    
    /**
     * 统计启用的规则数量
     */
    long countByEnabledTrue();
    
    /**
     * 统计特定优先级的规则数量
     */
    long countByPriority(RulePriority priority);
    
    /**
     * 查找包含特定关键词的规则
     */
    @Query("SELECT r FROM Rule r WHERE r.name LIKE %:keyword% OR r.description LIKE %:keyword% OR r.conditions LIKE %:keyword%")
    List<Rule> findByKeyword(@Param("keyword") String keyword);
    
    /**
     * 分页查找规则
     */
    Page<Rule> findByCategory(String category, Pageable pageable);
    
    /**
     * 分页查找启用的规则
     */
    Page<Rule> findByEnabledTrue(Pageable pageable);
}